/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * listCompra.java
 *
 * Created on 08/12/2011, 19:22:01
 */
package visao;

import compra.Compra;
import fachada.FachadaBDR;
import fornecedor.Fornecedor;
import funcionario.Funcionario;
import java.awt.Toolkit;
import java.sql.Date;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import solicitacaoCompra.SolicitacaoCompra;
import util.KeyValue;
import util.Util;

/**
 *
 * @author Alberto
 */
public class listCompra extends javax.swing.JFrame {
    
    public String[] titulos = new String [] {"#", "Descrição Produto", "Fornecedor", "Data Compra", "Valor Compra", "QTD Comprado", "Status"};
    public DefaultTableModel defTable;
    public CadCompra cadastroCompra = new CadCompra(0);

    /** Creates new form listCompra */
    public listCompra() {
        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            List<Compra> listCompra = objFachadaBDR.listarComprasAtivas();
            
            // Setando a tabela
            this.defTable =  atualizaLista(listCompra);

        } catch(Exception e){
            System.out.println(e.getMessage());
        }
        
        initComponents();
        // this.setSize(800, 600);
        //this.setTitle("PathLogistica");
        setIconImage(new ImageIcon(getClass().getResource("/Imagens/visao.gif")).getImage());
        this.setLocationRelativeTo(null);//Tela fica centralizada
        //this.setSize(Toolkit.getDefaultToolkit().getScreenSize());//deixa igual a tela
        this.setLocationRelativeTo(null);
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jComboBox_idFornecedor = new javax.swing.JComboBox();
        jComboBox_idSolicitacaoCompra = new javax.swing.JComboBox();
        jComboBox_idFuncionario = new javax.swing.JComboBox();
        jLabel_idFornecedor = new javax.swing.JLabel();
        jLabel_idSolicitacaoCompra = new javax.swing.JLabel();
        jLabel_idFuncionario = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jButton_Buscar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        mensagem = new javax.swing.JLabel();
        jButton_Editar = new javax.swing.JButton();
        jButton_Remover = new javax.swing.JButton();
        jButton_Atualizar = new javax.swing.JButton();
        jFormattedTextField_data_compra_inicial = new javax.swing.JFormattedTextField();
        jFormattedTextField_data_compra_final = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();

        setTitle("Compra");
        setResizable(false);

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            List<Fornecedor> listFornecedor = objFachadaBDR.listarFornecedor("");
            jComboBox_idFornecedor.addItem(new KeyValue("--- Favor Selecionar ---", "0"));
            for (Fornecedor objForn : listFornecedor) {
                jComboBox_idFornecedor.addItem(new KeyValue(objForn.getContato(), Integer.toString(objForn.getIdFornecedor())));
            }
        } catch (Exception e) {
        }
        jComboBox_idFornecedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox_idFornecedorActionPerformed(evt);
            }
        });

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            List<SolicitacaoCompra> listSolicitacaoCompra = objFachadaBDR.listarSolicitacaoCompra("");
            jComboBox_idSolicitacaoCompra.addItem(new KeyValue("--- Favor Selecionar ---", "0"));
            for (SolicitacaoCompra objSolicitacaoCompra : listSolicitacaoCompra) {
                jComboBox_idSolicitacaoCompra.addItem(new KeyValue(objSolicitacaoCompra.getDescricaoProduto().getDecsricaoProduto(), Integer.toString(objSolicitacaoCompra.getIdSolicitacaoCompra())));
            }
        } catch (Exception e) {
        }

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            List<Funcionario> listFuncionario = objFachadaBDR.listarFuncionario("");

            jComboBox_idFuncionario.addItem(new KeyValue("--- Favor Selecionar ---","0"));
            for (Funcionario objFuncionario : listFuncionario) {
                jComboBox_idFuncionario.addItem(new KeyValue(objFuncionario.getNome(), Integer.toString(objFuncionario.getIdFuncionario())));
            }

        } catch (Exception e) {
        }

        jLabel_idFornecedor.setText("Fornecedor :");

        jLabel_idSolicitacaoCompra.setText("Solicitação Compra :");

        jLabel_idFuncionario.setText("Funcionario :");

        jLabel1.setText("Data Inicial:");

        jButton_Buscar.setText("Buscar");
        jButton_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_BuscarActionPerformed(evt);
            }
        });

        jTable1.setModel(this.defTable);
        jScrollPane1.setViewportView(jTable1);

        jButton_Editar.setText("Editar");
        jButton_Editar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_EditarActionPerformed(evt);
            }
        });

        jButton_Remover.setText("Remover");
        jButton_Remover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_RemoverActionPerformed(evt);
            }
        });

        jButton_Atualizar.setText("Atualizar");
        jButton_Atualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AtualizarActionPerformed(evt);
            }
        });

        jFormattedTextField_data_compra_inicial = new JFormattedTextField(Util.setMascara("##/##/####"));
        jFormattedTextField_data_compra_inicial.setText("01/01/2001");

        jFormattedTextField_data_compra_final = new JFormattedTextField(Util.setMascara("##/##/####"));
        jFormattedTextField_data_compra_final.setText(Util.getDataAtual());

        jLabel2.setText("Data Final:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton_Editar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Atualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Remover, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(mensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel_idFornecedor, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel_idSolicitacaoCompra, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel_idFuncionario, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jComboBox_idFuncionario, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jComboBox_idSolicitacaoCompra, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jComboBox_idFornecedor, javax.swing.GroupLayout.Alignment.LEADING, 0, 275, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jFormattedTextField_data_compra_inicial, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(36, 36, 36)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jFormattedTextField_data_compra_final, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29)
                        .addComponent(jButton_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 632, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox_idFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel_idFornecedor))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jLabel_idSolicitacaoCompra))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox_idSolicitacaoCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox_idFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel_idFuncionario))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jFormattedTextField_data_compra_inicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jFormattedTextField_data_compra_final, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton_Buscar))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Editar)
                    .addComponent(jButton_Atualizar)
                    .addComponent(jButton_Remover))
                .addGap(18, 18, 18)
                .addComponent(mensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox_idFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_idFornecedorActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jComboBox_idFornecedorActionPerformed

    private void jButton_BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_BuscarActionPerformed
        try {
            // instanciando a fachada
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
            
            int idFornecedor = Integer.parseInt(((KeyValue) jComboBox_idFornecedor.getSelectedItem()).getValue());
            int idSolicitacaoCompra = Integer.parseInt(((KeyValue) jComboBox_idSolicitacaoCompra.getSelectedItem()).getValue());
            int idFuncionario = Integer.parseInt(((KeyValue) jComboBox_idFuncionario.getSelectedItem()).getValue());
            Date dataSolicitacaoInicial = Date.valueOf(Util.formatarDataBanco(jFormattedTextField_data_compra_inicial.getText()));
            Date dataSolicitacaoFinal = Date.valueOf(Util.formatarDataBanco(jFormattedTextField_data_compra_final.getText()));
            
//            idFornecedor, idSolicitacaoCompra, idFuncionario, dataSolicitacao
            
            // Listando as descrição produtos
            List<Compra> listCompra = objfaFachadaBDR.listarCompraPorFornecedorPorSolicitacaoPorFuncionarioPorData(idFornecedor, idSolicitacaoCompra, idFuncionario, dataSolicitacaoInicial, dataSolicitacaoFinal);
            
            // Setando a tabela
            this.defTable =  atualizaLista(listCompra);
            
            // Setando a nova listagem
            jTable1.setModel(this.defTable);
            jTable1.revalidate();
            
            if(listCompra.size() > 0)
                mensagem.setText("");
            else
                mensagem.setText("Nenhuma Descrição Produto encontrada!");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
}//GEN-LAST:event_jButton_BuscarActionPerformed

    private void jButton_EditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EditarActionPerformed
        try {
            // pegando a linha selecionada
            if(this.jTable1.getSelectedColumnCount() == 0) throw new Exception("Favor selecionar uma Compra!");
            
            // Pegando a linha que está selecionada
            int linha = this.jTable1.getSelectedRow();
            // recuperando o Cpf do funcionario
            int idCompra = (Integer) this.jTable1.getValueAt(linha,0);
            
            // se a tela de cargo ja estiver instanciada
            if(!this.cadastroCompra.isVisible()){
                this.cadastroCompra = new CadCompra(idCompra);
                this.cadastroCompra.setVisible(true);
            }
            
            // atualizando os cargos
            jTable1.revalidate();
            
            mensagem.setText("");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
}//GEN-LAST:event_jButton_EditarActionPerformed

    private void jButton_RemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_RemoverActionPerformed
        try {
            // pegando a linha selecionada
            if(this.jTable1.getSelectedColumnCount() == 0 || this.jTable1.getSelectedColumnCount() > 1) throw new Exception("Favor selecionar uma Descrição Produto");
            
            int cancelar = JOptionPane.showConfirmDialog(null, "Deseja Remover esta Solicitação Compra?");
            if (cancelar == JOptionPane.YES_OPTION) {
                try {
                    int linha = this.jTable1.getSelectedRow();
                    
                    // recuperando o Cpf do funcionario
                    int idCompra = (Integer) this.jTable1.getValueAt(linha,0);
                    
                    // instanciando a fachada
                    FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
                    
                    // Listando os cargos
                    objFachadaBDR.removerCompra(idCompra);
                    
                    // Listando os cargos
                    List<Compra> listCompra = objFachadaBDR.listarComprasAtivas();
                    
                    // Setando a tabela
                    this.defTable =  atualizaLista(listCompra);
                    
                    // Setando a nova listagem
                    jTable1.setModel(this.defTable);
                    
                    jTable1.revalidate();
                    
                    mensagem.setText("Removido com sucesso!");
                    
                } catch (Exception ex) {
                    mensagem.setText(ex.getMessage());
                }
            }
        } catch (Exception e) {
            mensagem.setText(e.getMessage());
        }
}//GEN-LAST:event_jButton_RemoverActionPerformed

    private void jButton_AtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AtualizarActionPerformed
        // TODO add your handling code here:
        try {
            // instanciando a fachada
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            
            List<Compra> listCompra = objFachadaBDR.listarComprasAtivas();
            
            // Setando a tabela
            this.defTable =  atualizaLista(listCompra);
            
            // Setando a nova listagem
            jTable1.setModel(this.defTable);
            
            jTable1.revalidate();
            mensagem.setText("");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
}//GEN-LAST:event_jButton_AtualizarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new listCompra().setVisible(true);
            }
        });
    }
    
    public DefaultTableModel atualizaLista(List<Compra> listCompra) {
        //{"#", "Descrição Produto", "Fornecedor", "Data Compra", "Valor Compra", "QTD Comprado", "Status"}
        Object[][] resposta = new Object[listCompra.size()][7];

        for (int i = 0; i < resposta.length; i++) {
            Compra objCompra = listCompra.get(i);

            resposta[i][0] = objCompra.getIdCompra();
            resposta[i][1] = objCompra.getSolicitacaoCompra().getDescricaoProduto().getDecsricaoProduto();
            resposta[i][2] = objCompra.getFornecedor().getDescricaoFornecedor();
            resposta[i][3] = Util.formatarBancoData(objCompra.getDataCompra().toString());
            resposta[i][4] = objCompra.getValorCompra();
            resposta[i][5] = objCompra.getQtdProduto();
            resposta[i][6] = objCompra.getStatusCompra() ? "Ativo" : "Inativo";
            
            
        }
        // Setando a tabela
        return new DefaultTableModel(resposta, titulos){   
              @Override  
              public boolean isCellEditable(int row, int col)   
              {   
                     return false;   
              }   
        };
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_Atualizar;
    private javax.swing.JButton jButton_Buscar;
    private javax.swing.JButton jButton_Editar;
    private javax.swing.JButton jButton_Remover;
    private javax.swing.JComboBox jComboBox_idFornecedor;
    private javax.swing.JComboBox jComboBox_idFuncionario;
    private javax.swing.JComboBox jComboBox_idSolicitacaoCompra;
    private javax.swing.JFormattedTextField jFormattedTextField_data_compra_final;
    private javax.swing.JFormattedTextField jFormattedTextField_data_compra_inicial;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel_idFornecedor;
    private javax.swing.JLabel jLabel_idFuncionario;
    private javax.swing.JLabel jLabel_idSolicitacaoCompra;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel mensagem;
    // End of variables declaration//GEN-END:variables
}
